/**
    @author: ChenLin
    @date: 2022/11/11
**/
package api

import (
	"../handler"
	"../service"
	"errors"
	"flamingo/flamingo_etcd"
	"flamingo/logger"
	"flamingo/server"
	"fmt"
	"github.com/golang/protobuf/proto"
	. "go/XXProtocols"
	"time"
)

type ThriftVideoServer struct {
	ThriftVideoService *service.ThriftVideoProcessService
	server.FlamingoBaseServer
}

func NewThriftVideoServer(ch chan handler.VideoProcess) *ThriftVideoServer {
	var server = &ThriftVideoServer{}
	server.ThriftVideoService = service.NewThriftVideoProcessService()
	server.ThriftVideoService.Ch = ch
	return server
}

func (self *ThriftVideoServer) Init() {
	thriftManager := &flamingo_etcd.FlamingoThriftBaseManager{}
	self.SetThriftManager(thriftManager)
	self.SetGetRequestFunc(self.PraseResult)
	self.SetCallBackProto(self.CallbackHandler)
}

func (self *ThriftVideoServer) CallbackHandler(request *XXUnitySSPkg, message proto.Message) (*XXUnitySSPkg, proto.Message) {
	start := time.Now()
	var response proto.Message
	if request == nil || message == nil {
		logger.Logln(logger.ERROR, "request is nil ")
		return nil, nil
	}
	var err error
	if request.ClientHead.GetCmd() == uint32(LiuLiuXDataProto_CMD_CMD_LiuLiuXDataProto) {
		reqProto := message.(*LiuLiuXDataProto)
		var response *LiuLiuXDataProto
		logger.Logln(logger.DEBUG, reqProto.String(), request.ClientHead.String())
		subcmd := uint32(reqProto.GetSubcmd())
		switch subcmd {
		case uint32(LiuLiuXDataProto_SUBCMD_SUBCMD_LiuLiuXDataProto_MJBannerReq):
		default:
			logger.Logln(logger.ERROR, "not found any subcmd")
		}
		if err != nil || response == nil {
			response = &LiuLiuXDataProto{
				Result: proto.Int32(int32(LiuLiuXDataProtoErrorCode_LiuLiuXDataProto_Err_Unknown)),
				Subcmd: proto.Int32(0),
			}
		}
		endTime := time.Now()
		logger.Logln(logger.ERROR, "request spend times ", endTime.Sub(start), subcmd)
		return request, response
	}
	return request, response
}

func (self *ThriftVideoServer) PraseResult(request *XXUnitySSPkg) (proto.Message, error) {
	var response proto.Message
	if request == nil || request.ClientHead == nil {
		return nil, errors.New("request is error")
	}
	if request.ClientHead.GetCmd() == uint32(LiuLiuXDataProto_CMD_CMD_LiuLiuXDataProto) {
		response = &LiuLiuXDataProto{}
	} else {
		return nil, errors.New(fmt.Sprintf("request is error cmd is error %d %d ", request.ClientHead.GetCmd(), uint32(LiuLiuXDataProto_CMD_CMD_LiuLiuXDataProto)))
	}
	err := proto.Unmarshal(request.GetBody(), response)
	if err != nil {
		logger.Logln(logger.ERROR, err)
		return nil, err
	}
	return response, nil
}
